package fr.efrei.musicpliz.dao.impl;

import java.math.BigInteger;
import java.util.List;

import javax.persistence.Query;
import javax.persistence.Query;

import fr.efrei.musicpliz.dao.MessageDao;
import fr.efrei.musicpliz.dto.CompteDto;
import fr.efrei.musicpliz.entity.Message;
import fr.efrei.musicpliz.enums.MessageStatus;

/**
 * Implementation of MessageDao interface
 */
public class MessageDaoImpl extends AbstractDaoImpl<Message> implements MessageDao {

	@Override
	@SuppressWarnings("unchecked")
	public List<Message> getReceived(CompteDto compte) {
		Query query = entityManager
			.createQuery("from Message where destinataire_id =:destinataire and compte_id = :compte");
		query.setParameter("destinataire", compte.getId());
		query.setParameter("compte", compte.getId());
		return (List<Message>) query.getResultList();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Message> getSent(CompteDto compte) {
		Query query = entityManager
			.createQuery("from Message where expediteur_id =:expediteur and compte_id = :compte");
		query.setParameter("expediteur", compte.getId());
		query.setParameter("compte", compte.getId());
		return (List<Message>) query.getResultList();
	}
	
	public int getNewReceivedCount(CompteDto compte){
		Query query = entityManager
			.createNativeQuery("select count(*) from Message where destinataire_id =:destinataire and status =:status and compte_id =:compte");
		query.setParameter("destinataire", compte.getId());
		query.setParameter("compte", compte.getId());
		query.setParameter("status", MessageStatus.UNREAD.ordinal());
		return ((BigInteger) query.getResultList().get(0)).intValue();
	}
	
}
